package 反射.取两个对象值不同的属性;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 *
 */
public abstract class AbstractEquator implements Equator {

    /**
     * 包装类集合
     */
    private static final List<Class<?>> WRAPPERS = Arrays.asList(Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Character.class, Boolean.class, String.class);

    public AbstractEquator() {
    }

    /**
     * 对象属性类型，是否是基本数据类型或其包装类
     *
     * @param oldObj
     * @param newObj
     * @return
     */
    protected boolean isSimpleField(Object oldObj, Object newObj) {
        boolean oldFlag = true;
        boolean newFlag = true;
        if (oldObj != null) {
            Class<?> oldClazz = oldObj.getClass();
            oldFlag = oldClazz.isPrimitive() || WRAPPERS.contains(oldClazz);
        }
        if (newObj != null) {
            Class<?> newClazz = newObj.getClass();
            newFlag = newClazz.isPrimitive() || WRAPPERS.contains(newClazz);
        }
        return oldFlag || newFlag;
    }

    /**
     * 是否需要添加到属性值不相等的数组中
     *
     * @param fieldName
     * @param oldVal
     * @param newVal
     * @return
     */
    protected boolean isDiff(String fieldName, Object oldVal, Object newVal) {
        //如果新值，旧值无任何意义，不记录
        if ((oldVal == null || oldVal == "") && (newVal == null || newVal == "")) {
            return false;
        }
        return !isEqual(oldVal, newVal);
    }

    /**
     * 判断值是否相等
     *
     * @param oldVal
     * @param newVal
     * @return
     */
    private boolean isEqual(Object oldVal, Object newVal) {
        return oldVal instanceof Collection && newVal instanceof Collection ? Objects.deepEquals(((Collection) oldVal).toArray(), ((Collection) newVal).toArray()) : Objects.deepEquals(oldVal, newVal);
    }
}
